`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    00:43:47 05/01/2012 
// Design Name: 
// Module Name:    alu 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module ALU2(
		input systemclock,
		input fsmAluReq,
		input [2:0] fsmAluOpt,
		input [16:0] chrAluData,
		input [16:0] stackAluData,
		
		output reg aluStackPop =0,
		output reg [1:0] aluChrEn,
		output reg [16:0] aluChrData

    );

		parameter ADD = 3'b001;
		parameter SUB = 3'b010;
		parameter MUL = 3'b100;
		parameter DIV = 3'b011;
		
		reg ALUflag =0;
		
		always @ (posedge systemclock) 
			if ( fsmAluReq ) begin

				aluStackPop = 1'b1;
				aluChrEn = 2'b01;	
				
				case ( fsmAluOpt )
					ADD: begin
						if (chrAluData[16]!=stackAluData[16]) begin

							if(chrAluData[15:0]>=stackAluData[15:0]) begin	

										aluChrData[16] = chrAluData[16];

										aluChrData[15:0] = chrAluData[15:0] - stackAluData[15:0];

										end

							else begin

									aluChrData[16] = stackAluData[16];

									aluChrData[15:0] = stackAluData[15:0] - chrAluData[15:0];

							end

						end

						else begin

								aluChrData[16] = chrAluData[16];

								aluChrData[15:0] = chrAluData[15:0] + stackAluData[15:0];

						end

						ALUflag <= 1;
					end
					
					SUB: begin
						if (chrAluData[16]!=stackAluData[16]) begin

							aluChrData[16] = chrAluData[16];

							aluChrData[15:0] = chrAluData[15:0] + stackAluData[15:0];

						end

						else begin

							if (chrAluData[15:0]>=stackAluData[15:0]) begin

								aluChrData[16] = 1'b0;

								aluChrData[15:0] = chrAluData[15:0] - stackAluData[15:0];

							end

							else begin

								aluChrData[16] = 1'b1;

								aluChrData[15:0] = stackAluData[15:0] - chrAluData[15:0];

							end

						end

						ALUflag <= 1;
					end
					
					MUL: begin
						aluChrData	= chrAluData * stackAluData;

						ALUflag <= 1;
					end
					
					DIV: begin
						//aluChrData = chrAluData + stackAluData;
					end

					default:;
				endcase
			end else if (ALUflag ==1)

					begin

					aluChrEn = 2'b10;
					aluStackPop = 1'b0;

					ALUflag <=0;

			end else begin

				aluStackPop	=1'b0;
				aluChrEn = 2'b00;

				end
endmodule
